package com.wyl.template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wyl.template.domain.common.ResponseResult;
import com.wyl.template.domain.model.SysPermissionDO;
import com.wyl.template.domain.model.SysRolePermissionDO;
import com.wyl.template.exception.BusinessException;
import com.wyl.template.exception.ErrorCodeEnum;
import com.wyl.template.mapper.SysRolePermissionMapper;
import com.wyl.template.service.SysRolePermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * <p>
 * 角色权限表 服务实现类
 * </p>
 *
 * @author wyl
 * @since 2021-06-11
 */
@Service
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermissionDO> implements SysRolePermissionService {
    @Autowired
    private SysRolePermissionMapper rolePermissionMapper;

    /**
     * 更新角色关联的权限
     *
     * @param roleId
     * @param list
     */
    @Override
    public ResponseResult updateRolePermission(Long roleId, List<SysRolePermissionDO> list) {
        if (roleId == null) {
            throw new BusinessException(ErrorCodeEnum.UPDATE_FAILURE);
        }
        // 先删除，再插入
        SysRolePermissionDO rolePermissionDO = new SysRolePermissionDO();
        rolePermissionDO.setRoleId(roleId);
        QueryWrapper<SysRolePermissionDO> queryWrapper = new QueryWrapper<>(rolePermissionDO);
        rolePermissionMapper.delete(queryWrapper);

        if (!ObjectUtils.isEmpty(list)) {
            if (!saveBatch(list)) {
                throw new BusinessException(ErrorCodeEnum.UPDATE_FAILURE);
            }
        }
        return ResponseResult.success();
    }

    /**
     * 根据权限id，删除相关记录
     *
     * @param permissionId
     * @return
     */
    @Override
    public ResponseResult deleteRolePermissionByPermissionId(Long permissionId) {
        if (permissionId == null) {
            throw new BusinessException(ErrorCodeEnum.DELETE_ROLE_PER_BY_PER_ERR);
        }
        // 先删除，再插入
        SysRolePermissionDO rolePermissionDO = new SysRolePermissionDO();
        rolePermissionDO.setPermissionId(permissionId);
        QueryWrapper<SysRolePermissionDO> queryWrapper = new QueryWrapper<>(rolePermissionDO);
        rolePermissionMapper.delete(queryWrapper);

        return ResponseResult.success();
    }
}
